package com.lgmshare.k3.ui.base;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lgmshare.component.utils.UIUtils;
import com.lgmshare.component.widget.StatusLayout;
import com.lgmshare.component.widget.recyclerview.RecyclerViewAdapter;
import com.lgmshare.component.widget.recyclerview.RecyclerViewHeaderFooterAdapter;
import com.lgmshare.k3.R;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public abstract class BaseListFragment<T> extends BaseFragment implements RecyclerViewAdapter.OnItemClickListener,
        RecyclerViewHeaderFooterAdapter.OnHeaderClickListener,
        RecyclerViewHeaderFooterAdapter.OnFooterClickListener {

    private static final int LOAD_SUCCESS = 0;
    private static final int LOAD_FAILURE = 1;

    @BindView(R.id.refreshLayout)
    protected SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    protected RecyclerView recyclerView;
    @BindView(R.id.statusLayout)
    protected StatusLayout statusLayout;

    protected boolean mLazyVisible = false;

    protected RecyclerViewHeaderFooterAdapter<T> mRecyclerAdapter;
    private int mPageIndex = 1;

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("lazyVisible", mLazyVisible);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null) {
            mLazyVisible = savedInstanceState.getBoolean("lazyVisible", mLazyVisible);
        }
    }

    @Override
    protected int onBindLayoutResId() {
        return R.layout.base_pull_list_fragment;
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initView() {
        super.initView();
        statusLayout.setErrorButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onListPullReload();
            }
        });

        mRecyclerAdapter = onListCreateAdapter();
        mRecyclerAdapter.setOnItemClickListener(this);

        recyclerView.setItemAnimator(null);//设置动画为null来解决闪烁问题
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(mRecyclerAdapter);
        //刷新
        /*refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));*/
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pullRefresh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                pullLoadMore();
            }
        });
    }

    @Override
    protected void initLoad() {
        mLazyVisible = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mLazyVisible) {
            mLazyVisible = false;
            onListLoadData();
        }
    }

    @Override
    public void onHeaderClick(int index) {
    }

    @Override
    public void onFooterClick(int index) {
    }

    @Override
    public void onItemClick(View view, int position) {
    }

    /**
     * 添加数据到列表顶部
     *
     * @param t
     */
    protected void onListAddDataToTop(T t) {
        statusLayout.hide();
        mRecyclerAdapter.addItem(0, t);
        mRecyclerAdapter.notifyDataSetChanged();
        UIUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                recyclerView.scrollToPosition(0);
            }
        }, 500);
    }

    /**
     * 加载
     */
    protected void onListLoadData() {
        mPageIndex = 1;
        if (mRecyclerAdapter.getDataCount() == 0) {
            statusLayout.setLoadingMessage("正在加载数据...");
            statusLayout.showLoading();
        }
        onListPullLoad(mPageIndex);
    }

    /**
     * 重新加载
     */
    protected void onListPullReload() {
        if (mLazyVisible) {
            return;
        }
        if (mRecyclerAdapter.getDataCount() == 0) {
            statusLayout.setLoadingMessage("正在加载数据...");
            statusLayout.showLoading();
        }
        onListPullLoad(mPageIndex);
    }

    /**
     * pull网络请求成功处理
     *
     * @param list
     * @param totalSize
     */
    protected void onListPullLoadSuccess(List<T> list, int totalSize) {
        if (list == null) {
            list = new ArrayList<>();
        }
        if (mPageIndex == 1) {
            //刷新成功
            mRecyclerAdapter.setList(list);
        } else {
            //加载更多成功
            mRecyclerAdapter.addList(list);
        }

        List<T> dataList = mRecyclerAdapter.getList();
        //是否有下一页
        if (dataList != null && dataList.size() < totalSize) {
            refreshLayout.setEnableLoadMore(true);
        } else {
            refreshLayout.setEnableLoadMore(false);
        }
        //是否为空数据
        if (dataList == null || dataList.size() == 0) {
            statusLayout.setEmptyMessage("暂无数据");
            statusLayout.showEmpty();
        } else {
            statusLayout.hide();
        }
        pullResultHandle(LOAD_SUCCESS);
    }

    /**
     * pull网络请求失败处理
     *
     * @param emptyMsg
     */
    protected void onListPullLoadEmpty(String emptyMsg) {
        statusLayout.setEmptyMessage(emptyMsg);
        statusLayout.showEmpty();
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.finishRefresh(false);
        refreshLayout.finishLoadMore(false);
        pullResultHandle(LOAD_FAILURE);
    }

    /**
     * pull网络请求失败处理
     *
     * @param errorMsg
     */
    protected void onListPullLoadFailure(String errorMsg) {
        if (mPageIndex > 1) {
            mPageIndex--;
        }
        if (mRecyclerAdapter.getDataCount() > 0) {
            showToast(errorMsg);
            statusLayout.hide();
        } else {
            statusLayout.setErrorMessage(errorMsg);
            statusLayout.showError();
        }
        pullResultHandle(LOAD_FAILURE);
    }

    /**
     * 执行下拉刷新操作
     */
    private void pullRefresh() {
        mPageIndex = 1;
        refreshLayout.setEnableLoadMore(false);
        onListPullLoad(mPageIndex);
    }

    /**
     * 执行上拉加载更多操作
     */
    private void pullLoadMore() {
        mPageIndex++;
        onListPullLoad(mPageIndex);
    }

    private void pullResultHandle(int result) {
        switch (result) {
            case LOAD_FAILURE:
                refreshLayout.finishRefresh(false);
                refreshLayout.finishLoadMore(false);
                break;
            case LOAD_SUCCESS:
                refreshLayout.finishRefresh(0);
                refreshLayout.finishLoadMore(0);
                break;
            default:
                break;
        }
    }

    /**
     * the data for this ListAdapter should be set here
     *
     * @return
     */
    protected abstract RecyclerViewHeaderFooterAdapter onListCreateAdapter();

    /**
     * 执行刷新加载操作
     */
    protected abstract void onListPullLoad(int pageIndex);
}
